<script setup>
import { ref, reactive } from 'vue'
import { ElMessage } from 'element-plus'
import {userStore} from "@/store/index.js";
import axios from "axios";

const formRef = ref()
const userItemStore = userStore()
const form = reactive({
  oldPassword: '',
  newPassword: '',
  confirmPassword: ''
})

const validateConfirmPassword = (rule, value, callback) => {
  if (value !== form.newPassword) {
    callback(new Error('两次输入的密码不一致'))
  } else {
    callback()
  }
}

const rules = reactive({
  oldPassword: [
    { required: true, message: '请输入旧密码', trigger: 'blur' },
    { min: 6, max: 20, message: '密码长度在6到20个字符', trigger: 'blur' }
  ],
  newPassword: [
    { required: true, message: '请输入新密码', trigger: 'blur' },
    { min: 6, max: 20, message: '密码长度在6到20个字符', trigger: 'blur' }
  ],
  confirmPassword: [
    { required: true, message: '请再次输入新密码', trigger: 'blur' },
    { validator: validateConfirmPassword, trigger: 'blur' }
  ]
})

const handleSubmit = () => {
axios.post(`user/updatePassword/${userItemStore.user.id}/${form.confirmPassword}`).then(res => {
ElMessage.success("修改密码成功")
}).catch(err=>{
  ElMessage.error("修改失败");
})
}

const handleCancel = () => {
  formRef.value.resetFields()
}
</script>

<template>
  <div class="account-settings">
    <h2 class="settings-title">账号设置</h2>

    <el-form
        ref="formRef"
        :model="form"
        :rules="rules"
        label-width="120px"
        class="settings-form"
    >
      <el-form-item label="旧密码" prop="oldPassword">
        <el-input
            v-model="form.oldPassword"
            type="password"
            placeholder="请输入"
            show-password
        />
      </el-form-item>

      <el-form-item label="新密码" prop="newPassword">
        <el-input
            v-model="form.newPassword"
            type="password"
            placeholder="请输入"
            show-password
        />
      </el-form-item>

      <el-form-item label="确认密码" prop="confirmPassword">
        <el-input
            v-model="form.confirmPassword"
            type="password"
            placeholder="请输入"
            show-password
        />
      </el-form-item>

      <el-form-item class="form-actions">
        <el-button @click="handleCancel">取消</el-button>
        <el-button type="primary" @click="handleSubmit">确定</el-button>
      </el-form-item>
    </el-form>
  </div>
</template>

<style scoped>
.account-settings {
  max-width: 600px;
  margin: 0 auto;
  padding: 20px;
  background-color: #fff;
  border-radius: 8px;
  box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1);
}

.settings-title {
  text-align: center;
  margin-bottom: 30px;
  color: #333;
}

.settings-form {
  padding: 0 20px;
}

.form-actions {
  display: flex;
  justify-content: center;
  margin-top: 30px;
}

.form-actions .el-button {
  margin: 0 10px;
  width: 100px;
}
</style>